// wssocketShared.js 用于管理WebSocket连接，支持多页面协同工作，避免重复连接

var websock = null;
let rec; //断线重连后，延迟5秒重新创建WebSocket连接  rec用来存储延迟请求的代码
let isConnect = false; //连接标识 避免重复连接
let connectCallBack = null;
let messageCallBack = null;
let closeCallBack = null;

// 添加BroadcastChannel支持
let channel = null;
let isMaster = false; // 标识当前页面是否为主连接
let isProcessingBroadcast = false; // 防止广播消息处理时产生循环
let hasMasterResponse = false; // 标记是否收到主连接响应

// 检查浏览器是否支持BroadcastChannel
const isBroadcastChannelSupported = typeof BroadcastChannel !== 'undefined';

// 安全发送消息到BroadcastChannel的辅助函数
const safePostMessage = (message) => {
  if (channel && isBroadcastChannelSupported) {
    try {
      channel.postMessage(message);
    } catch (e) {
      console.warn('BroadcastChannel发送消息失败:', e);
    }
  }
};

// 初始化BroadcastChannel
const initChannel = () => {
  if (isBroadcastChannelSupported && !channel) {
    try {
      channel = new BroadcastChannel('websocket_manager');
      setupChannelListeners();
    } catch (e) {
      console.warn('初始化BroadcastChannel失败:', e);
      channel = null;
    }
  }
};

// 设置BroadcastChannel监听器
const setupChannelListeners = () => {
  if (!channel) return;

  channel.onmessage = function (event) {
    const { type, data } = event.data;
    // console.log('onmessage', type, data);

    switch (type) {
      case 'MASTER_CHECK':
        // 如果当前页面已连接，宣告自己是主连接
        if (isConnect) {
          safePostMessage({ type: 'MASTER_RESPONSE' });
        }
        break;
      case 'MASTER_RESPONSE':
        // 有其他页面已经是主连接
        hasMasterResponse = true;
        isMaster = false;
        break;
      case 'MESSAGE_BROADCAST':
        // 接收到来自服务器的消息广播
        if (messageCallBack) {
          isProcessingBroadcast = true;
          messageCallBack(data.cmd, data.data);
          isProcessingBroadcast = false;
        }
        break;
      case 'CONNECTION_STATUS':
        // 接收连接状态更新
        if (data.status === 'connected') {
          isConnect = true;
          if (connectCallBack && !isProcessingBroadcast) {
            isProcessingBroadcast = true;
            connectCallBack();
            isProcessingBroadcast = false;
          }
        } else if (data.status === 'disconnected' || data.status === 'closed') {
          isConnect = false;
          isMaster = false;
          hasMasterResponse = false;
        }
        break;
      case 'SEND_MESSAGE':
        // 从页面要求主连接发送消息
        if (isMaster) {
          sendMessage(data);
        }
        break;
      case 'LOCAL_MESSAGE_BROADCAST':
        // 接收本地发送消息的广播
        if (messageCallBack) {
          isProcessingBroadcast = true;
          messageCallBack(data.cmd, data.data);
          isProcessingBroadcast = false;
        }
        // 主连接也需要处理这些消息
        if (isMaster && messageCallBack && !isProcessingBroadcast) {
          isProcessingBroadcast = true;
          messageCallBack(data.cmd, data.data);
          isProcessingBroadcast = false;
        }
        break;
      case 'MESSAGE_READ_BROADCAST':
        // 接收消息已读状态同步
        if (messageCallBack) {
          isProcessingBroadcast = true;
          messageCallBack(data.cmd, data.data);
          isProcessingBroadcast = false;
        }
        break;
    }
  };
};

// 初始化BroadcastChannel
if (isBroadcastChannelSupported) {
  initChannel();
}

let connect = (wsurl, accessToken) => {
  // 重置状态
  hasMasterResponse = false;

  // 检查是否支持多页面协同
  if (isBroadcastChannelSupported) {
    // 确保channel已初始化
    initChannel();
    // 检查是否已经有页面建立了连接
    safePostMessage({ type: 'MASTER_CHECK' });

    // 延长检查时间，确保有足够时间接收响应
    setTimeout(() => {
      // console.log('检查结果: hasMasterResponse=', hasMasterResponse, 'isConnect=', isConnect, 'isMaster=', isMaster);
      if (!hasMasterResponse && !isConnect) {
        // 成为主连接
        isMaster = true;
        establishWebSocketConnection(wsurl, accessToken);
      } else if (hasMasterResponse || isConnect) {
        // 已有连接，触发连接回调
        if (connectCallBack) {
          connectCallBack();
        }
      }
    }, 300); // 增加到300ms确保有足够时间接收响应
  } else {
    // 浏览器不支持BroadcastChannel，使用原有逻辑
    establishWebSocketConnection(wsurl, accessToken);
  }
};

// 原有的WebSocket连接逻辑提取为独立函数
let establishWebSocketConnection = (wsurl, accessToken) => {
  try {
    if (isConnect) {
      return;
    }
    console.log("连接WebSocket");
    websock = new WebSocket(wsurl);
    websock.onmessage = function (e) {
      let sendInfo = JSON.parse(e.data);

      if (isMaster && isBroadcastChannelSupported) {
        // 作为主连接，广播来自服务器的消息给其他页面
        if (sendInfo.cmd !== 0 && sendInfo.cmd !== 1) {
          safePostMessage({
            type: 'MESSAGE_BROADCAST',
            data: sendInfo
          });
        }
      }

      if (sendInfo.cmd == 0) {
        isConnect = true;
        heartCheck.start();
        // 登录成功才算真正完成连接
        if (connectCallBack) {
          connectCallBack();
        }

        // 广播连接状态
        if (isMaster && isBroadcastChannelSupported) {
          safePostMessage({
            type: 'CONNECTION_STATUS',
            data: { status: 'connected' }
          });
        }

        console.log('WebSocket登录成功');
      } else if (sendInfo.cmd == 1) {
        // 重新开启心跳定时
        heartCheck.reset();
      } else {
        // 其他消息转发出去
        if (messageCallBack) {
          messageCallBack(sendInfo.cmd, sendInfo.data);
        }
      }
    };

    websock.onclose = function (e) {
      console.log('WebSocket连接关闭');
      isConnect = false; //断开后修改标识
      isMaster = false;
      hasMasterResponse = false;

      // 广播连接关闭状态
      if (isMaster && isBroadcastChannelSupported) {
        safePostMessage({
          type: 'CONNECTION_STATUS',
          data: { status: 'disconnected', eventData: e }
        });
      }

      if (closeCallBack) {
        closeCallBack(e);
      }
    };

    websock.onopen = function () {
      console.log("WebSocket连接成功");
      // 发送登录命令
      let loginInfo = {
        cmd: 0,
        data: {
          accessToken: accessToken
        }
      };
      websock.send(JSON.stringify(loginInfo));
    };

    // 连接发生错误的回调方法
    websock.onerror = function () {
      console.log('WebSocket连接发生错误');
      isConnect = false; //连接断开修改标识
      isMaster = false;
      hasMasterResponse = false;
      reconnect(wsurl, accessToken);
    }
  } catch (e) {
    console.log("尝试创建连接失败");
    isConnect = false;
    isMaster = false;
    hasMasterResponse = false;
    reconnect(wsurl, accessToken); //如果无法连接上webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
  }
};

//定义重连函数
let reconnect = (wsurl, accessToken) => {
  console.log("尝试重新连接");
  if (isConnect) {
    //如果已经连上就不在重连了
    return;
  }
  rec && clearTimeout(rec);
  rec = setTimeout(function () { // 延迟5秒重连  避免过多次过频繁请求重连
    connect(wsurl, accessToken);
  }, 15000);
};

//设置关闭连接
let close = (code) => {
  // 关闭时通知其他页面
  if (isMaster && isBroadcastChannelSupported && channel) {
    try {
      channel.postMessage({
        type: 'CONNECTION_STATUS',
        data: { status: 'closed' }
      });
    } catch (e) {
      console.warn('发送关闭状态消息失败:', e);
    }
    channel.close();
    channel = null; // 清除引用
  }
  if (websock) {
    websock.close(code);
  }
  // 重置状态
  isMaster = false;
  isConnect = false;
  hasMasterResponse = false;
};

//心跳设置
let heartCheck = {
  timeout: 5000, //每段时间发送一次心跳包 这里设置为20s
  timeoutObj: null, //延时发送消息对象（启动心跳新建这个对象，收到消息后重置对象）
  start: function () {
    if (isConnect) {
      console.log('发送WebSocket心跳');
      let heartBeat = {
        cmd: 1,
        data: {}
      };
      if (websock && websock.readyState === websock.OPEN) {
        websock.send(JSON.stringify(heartBeat));
      }
    }
  },

  reset: function () {
    clearTimeout(this.timeoutObj);
    this.timeoutObj = setTimeout(function () {
      heartCheck.start();
    }, this.timeout);
  }
};

// 实际调用的方法
let sendMessage = (agentData) => {
  // 如果支持多页面且不是主连接，通过channel通知主连接发送
  if (isBroadcastChannelSupported && !isMaster && channel) {
    safePostMessage({
      type: 'SEND_MESSAGE',
      data: agentData
    });

    // 同时广播本地消息给所有页面（包括自己）
    safePostMessage({
      type: 'LOCAL_MESSAGE_BROADCAST',
      data: agentData
    });
    return;
  }

  // 主连接的情况
  if (websock && websock.readyState === websock.OPEN) {
    // 发送到服务器
    websock.send(JSON.stringify(agentData));

    // 如果是主连接且支持BroadcastChannel，广播本地消息给其他页面
    if (isMaster && isBroadcastChannelSupported && channel) {
      safePostMessage({
        type: 'LOCAL_MESSAGE_BROADCAST',
        data: agentData
      });
    }

    // 主连接也需要触发本地消息回调，确保自己能看到发送的消息
    if (messageCallBack && !isProcessingBroadcast) {
      isProcessingBroadcast = true;
      messageCallBack(agentData.cmd, agentData.data);
      isProcessingBroadcast = false;
    }
  } else if (websock && websock.readyState === websock.CONNECTING) {
    // 若是 正在开启状态，则等待1s后重新调用
    setTimeout(function () {
      sendMessage(agentData);
    }, 1000);
  } else {
    // 若未开启 ，则等待1s后重新调用
    setTimeout(function () {
      sendMessage(agentData);
    }, 1000);
  }
};

// 添加发送已读状态同步的方法
let sendReadStatus = (readData) => {
  // 防止处理广播消息时再次广播造成循环
  if (isProcessingBroadcast) {
    return;
  }

  if (isBroadcastChannelSupported && channel) {
    safePostMessage({
      type: 'MESSAGE_READ_BROADCAST',
      data: {
        cmd: readData.cmd,
        data: readData.data
      }
    });
  }

  // 如果是主连接，也发送到服务器
  if (isMaster && websock && websock.readyState === websock.OPEN) {
    websock.send(JSON.stringify(readData));
  } else if (!isMaster && isBroadcastChannelSupported) {
    // 从连接通过channel通知主连接发送已读状态
    safePostMessage({
      type: 'SEND_MESSAGE',
      data: readData
    });
  }
};

let onConnect = (callback) => {
  connectCallBack = callback;
};

let onMessage = (callback) => {
  messageCallBack = callback;
};

let onClose = (callback) => {
  closeCallBack = callback;
};

// 将方法暴露出去
export {
  connect,
  reconnect,
  close,
  sendMessage,
  sendReadStatus,
  onConnect,
  onMessage,
  onClose,
};